<?php
/**
 * Login with LightOpenID to google.com
 * 
 * @author Sean
 */

require 'openid.php';
include ("config.php");

define('SERVER_HOST', 'sean.servern.org/webdrop');

define('MYSQL_HOST', 'localhost');
define('MYSQL_USERNAME', 'webdrop');
define('MYSQL_PASSWORD', 'webdrop');
define('MYSQL_CHARSET', 'utf-8');
define('MYSQL_DATABASE', 'webdrop');


// The hostname of the server.
$cfg_hostname = SERVER_HOST;

// The name of the FORM element that holds the provider url.
$cfg_openid_provider_element_id = 'url';

// The name of the FORM element that holds the client url (custom)
$cfg_openoid_client_element_id = 'client_url';

$openid = new LightOpenID($cfg_hostname);

if (!$openid->mode)
{
	// User want to login
		
	if (isset($_POST[$cfg_openid_provider_element_id])) 
	{
		$openid->identity = $_POST[$cfg_openid_provider_element_id];
		
		// Add the client url to the return url.
		$openid->returnUrl = $openid->returnUrl . "?" . $cfg_openoid_client_element_id . "=" . urlencode($_POST[$cfg_openoid_client_element_id]);
		
		// Request additional data
		$openid->required = array('contact/email', 'namePerson/first', 'namePerson/last');
		
		header('Location: ' . $openid->authUrl());
    }
    else
    {
		die('Invalid login request sent to server.');
	}
}
else if ($openid->mode == 'cancel')
{
	// User cancelled login
	header('Location: ' . urldecode($_GET[$cfg_openoid_client_element_id]). '#page=login;status=cancelled');
}
else if ($openid->validate())
{
	// User successfully logged in!
	
	// Generate sessionId
	session_start();

	session_regenerate_id();
	$sessionId = session_id();
	
	session_destroy();
	
	// Get attributes from Google	
	$attr = $openid->getAttributes();
	
	$email = $attr['contact/email'];
	$firstName = $attr['namePerson/first'];
	$lastName = $attr['namePerson/last'];
	$fullName = $firstName . " " . $lastName;
	
	$url = preg_split("/=/", $openid->identity);
	
	$googleId = $url[1];
	
	// Search Database for user	
	@mysql_connect(MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD) or die('Unable to connect to database.');
	
	// Ensure correct charset
	mysql_set_charset(MYSQL_CHARSET); 
	
	@mysql_select_db(MYSQL_DATABASE) or die("Unable to select database.");
	
	$result = mysql_query("SELECT userID FROM users WHERE userID = '" . $email . "'");
	$result_count = mysql_numrows($result);
	
	if ($result_count < 1)
	{
		// The user is not registered, register him

		// creates directory for the user
		$location = $pathToUsersFiles.mysql_real_escape_string($googleId);
		$result = is_dir($location);
		if(!$result){
			mkdir($location, 0777);
		}
		
		$thumbDir = $pathToUsersFiles.mysql_real_escape_string($googleId)."/thumbs/";
		if(!$result = is_dir($thumbDir)){
			mkdir($thumbDir, 0777);
			 echo "Creating dir <br />";
		}
		$galleryDir = $pathToUsersFiles.mysql_real_escape_string($googleId)."/gallery/";
		if(!$result = is_dir($galleryDir)){
			mkdir($galleryDir, 0777);
			 echo "Creating dir <br />";
		}
		
		mysql_query("INSERT INTO users (googleID, userID, sessionID,  name) VALUES ('" . mysql_real_escape_string($googleId) . "', '" . mysql_real_escape_string($email) . "', '" . mysql_real_escape_string($sessionId) . "',  '" . mysql_real_escape_string($fullName) . "')");
	}
	else
	{		
		// User already registered.
	
		// creates directory for the user
		$location = $pathToUsersFiles.mysql_real_escape_string($googleId);
		$result = is_dir($location);
		if(!$result){
			mkdir($location, 0777);
		}
		
		$thumbDir = $pathToUsersFiles.mysql_real_escape_string($googleId)."/thumbs/";
		if(!$result = is_dir($thumbDir)){
			mkdir($thumbDir, 0777);
			 echo "Creating dir <br />";
		}
		
		$galleryDir = $pathToUsersFiles.mysql_real_escape_string($googleId)."/gallery/";
		if(!$result = is_dir($galleryDir)){
			mkdir($galleryDir, 0777);
			 echo "Creating dir <br />";
		}	

		// Update lastLogin, sessionId
		mysql_query("UPDATE users SET sessionID = '" . mysql_real_escape_string($sessionId) . "' WHERE userID = '" . mysql_real_escape_string($email) . "'");
	}
	
	mysql_close();
	
	// Get the client url from GET and return
	header('Location: ' . urldecode($_GET[$cfg_openoid_client_element_id]) . '#page=login;status=accepted;sessionid=' . $sessionId . ';googleid=' . $googleId . ';userid=' . $email);
}
else
{
	// User failed to login...
	header('Location: ' . urldecode($_GET[$cfg_openoid_client_element_id]) . '#page=login;status=denied');
}

